library(survey)
library(dplyr)
library(ggplot2)
library(gridExtra)

# Creating Figure 6.7
# Wave 2

# Create binaries for treatment group and controls for Q25A
# P_ASSIGN3A (0 control, 1 oppose, 2 support)
df$Q25A_opp[df$P_ASSIGN3A == 1] <- 0
df$Q25A_opp[df$P_ASSIGN3A == 2] <- 1

df$Q25A_sup[df$P_ASSIGN3A == 1] <- 0
df$Q25A_sup[df$P_ASSIGN3A == 3] <- 1

# Code agreement with Insurrection Act
df$Q25A2[df$Q25A < 77] <- 0
df$Q25A2[df$Q25A < 3] <- 1
df2 <- df[!is.na(df$Q25A2),]
summary(factor(df2$Q25A2))

# drop NA
df2_opp <- df2[!is.na(df2$Q25A_opp),]
df2_sup <- df2[!is.na(df2$Q25A_sup),]
df2_sup <- df2_sup[!is.na(df2_sup$party),]

# Creating weighted survey design objects
w2_design_opp <-
  svydesign(
    id = ~ 1,
    weights = ~ weight2,
    data = df2_opp
  )

w2_design_sup <-
  svydesign(
    id = ~ 1,
    weights = ~ weight2,
    data = df2_sup
  )


# Oppose
w2o_d <- svyttest(Q25A2~Q25A_opp, w2_design_opp[w2_design_opp$variables$party==0])
w2o_r <- svyttest(Q25A2~Q25A_opp, w2_design_opp[w2_design_opp$variables$party==2])

# Supports
w2s_d <- svyttest(Q25A2~Q25A_sup, w2_design_sup[w2_design_sup$variables$party==0])
w2s_r <- svyttest(Q25A2~Q25A_sup, w2_design_sup[w2_design_sup$variables$party==2])


# Wave 2
pt.est1 <- c(w2o_d$estimate,1,w2o_r$estimate,1,1,1,w2s_d$estimate,1,
             w2s_r$estimate)
ci.low1 <- c(w2o_d$conf.int[1],.9,w2o_r$conf.int[1],.9,.9,.9,w2s_d$conf.int[1],.9,
             w2s_r$conf.int[1])
ci.high1 <- c(w2o_d$conf.int[2],1.1, w2o_r$conf.int[2], 1.1,1.1,1.1, w2s_d$conf.int[2],1.1,
              w2s_r$conf.int[2])
plot.labs <- c(" ","Oppose","","  ","    ","     ","           ",
               "Support","        ")
df.plot1 <- data.frame(Treatment=plot.labs, estimate=pt.est1, 
                       lower=ci.low1, upper=ci.high1)
df.plot1$Treatment <- factor(df.plot1$Treatment, levels = plot.labs)

plot_w2 <- ggplot()+
  geom_pointrange(data=df.plot1, 
                  mapping = aes(x=Treatment,
                                y=estimate,
                                ymin=lower,
                                ymax=upper),
                  size = 0.5, color = c('blue','gray10','red','gray10','gray10','gray10',
                                        'blue','gray10','red'))+
  geom_hline(yintercept = 0, color = "black")+
  ylim(-.2,.2)+
  ylab("Difference in Means from Control Condition")+
  xlab("Treatment Condition")+
  theme_bw()

